package cn.bfay.lion.rest.mq;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import cn.bfay.cache.redis.RedisKeyBuilder;
import cn.bfay.cache.redis.RedisTime;
import cn.bfay.cache.redis.RedisUtils;
import cn.bfay.lion.rest.client.rsp.ProductDetailInfoRsp;
import cn.bfay.lion.rest.client.rsp.ProductInfoRsp;
import cn.bfay.lion.rest.entity.UserProduct;
import cn.bfay.lion.rest.manager.JingdongManager;
import cn.bfay.lion.rest.mapper.UserProductMapper;
import cn.bfay.lion.rest.redis.RedisKeyTemplate;
import cn.bfay.lion.rest.redis.RedisValueHelper;
import cn.bfay.lion.util.DateUtils;
import cn.bfay.lion.util.JsonUtils;
import cn.bfay.lion.util.NumberUtils;
import cn.bfay.wechat.WechatCoreUtil;
import cn.bfay.wechat.model.TemplateMessageNoticeData;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * NoticeConsumer.
 *
 * @author wangjiannan
 */
@RequiredArgsConstructor
@Component
@RabbitListener(queues = ("${jingdong.product.discount.notice.queue}"))
public class NoticeConsumer {
    private static final Logger log = LoggerFactory.getLogger(NoticeConsumer.class);

    @Value("${wechat.debug:false}")
    private boolean wechatDebug;

    private final UserProductMapper userProductMapper;
    private final WechatCoreUtil wechatCoreUtil;
    private final JingdongManager jingdongManager;

    @RabbitHandler
    public void procesNotice(String content) {
        String[] contentArr = content.split("\\|\\+\\|");
        log.debug("接收到的通知消息:ProductDetailInfo={}", contentArr[0]);
        log.debug("接收到的通知消息:ProductInfo={}", contentArr[1]);
        if (wechatDebug) {
            return;
        }

        try {
            ProductDetailInfoRsp productDetailInfoRsp = JsonUtils.json2Bean(contentArr[0], ProductDetailInfoRsp.class);
            ProductInfoRsp productInfoRsp = JsonUtils.json2Bean(contentArr[1], ProductInfoRsp.class);
            String name = productInfoRsp.getName();
            if (productDetailInfoRsp.getFinalPlusPrice() / productDetailInfoRsp.getPlusPrice() < 0.2) {
                doAdmin(productDetailInfoRsp, name);
            }

            String skuid = productDetailInfoRsp.getSkuid();
            List<UserProduct> userProducts = userProductMapper.selectList(new QueryWrapper<UserProduct>().lambda()
                .eq(UserProduct::getSkuid, skuid)
                .eq(UserProduct::getMark, (byte) 1));
            if (CollectionUtils.isEmpty(userProducts)) {
                return;
            }
            userProducts.forEach(userProduct -> {
                String openid = userProduct.getOpenid();
                if (productDetailInfoRsp.getFinalPlusPrice() > userProduct.getNoticePrice()) {
                    return;
                }
                // 查看缓存;存在并且和缓存数据一致不在往下走发送通知
                String redisKey = RedisKeyBuilder.generateRedisKey(RedisKeyTemplate.NOTICE_TEMPLATE,
                    (openid + "-notice-" + skuid));
                String redisValue = RedisUtils.getValue(redisKey);
                if (StringUtils.isNotEmpty(redisValue)
                    && NumberUtils.doubleEquals(Double.parseDouble(redisValue), productDetailInfoRsp.getFinalPlusPrice())) {
                    return;
                }
                // 发送通知
                sendMessage(openid, productDetailInfoRsp, name);
                // 发送通知成功放缓存
                RedisUtils.setValue(redisKey, String.valueOf(productDetailInfoRsp.getFinalPlusPrice()),
                    DateUtils.todayEndExpireSeconds() + RedisTime.DAY + RedisTime.HNOUR * 12);
            });
        } catch (Exception e) {
            log.error("消息消费错误", e);
        }
    }

    private void doAdmin(ProductDetailInfoRsp productDetailInfoRsp, String name) {
        String openid="o1Trh0o7NowjfJcOXRfjZ4KdOWis";
        // 查看缓存;存在并且和缓存数据一致不在往下走发送通知
        String redisKey = RedisKeyBuilder.generateRedisKey(RedisKeyTemplate.NOTICE_TEMPLATE,
                (openid + "-notice-admin-" + productDetailInfoRsp.getSkuid()));
        String redisValue = RedisUtils.getValue(redisKey);
        if (StringUtils.isNotEmpty(redisValue)
                && NumberUtils.doubleEquals(Double.parseDouble(redisValue), productDetailInfoRsp.getFinalPlusPrice())) {
            return;
        }
        // 发送通知
        sendMessage(openid, productDetailInfoRsp, name);
        // 发送通知成功放缓存
        RedisUtils.setValue(redisKey, String.valueOf(productDetailInfoRsp.getFinalPlusPrice()),
                DateUtils.todayEndExpireSeconds() + RedisTime.DAY + RedisTime.HNOUR * 12);
    }

    private void sendMessage(String openid, ProductDetailInfoRsp productDetailInfoRsp, String name) {
        String promotionLink = jingdongManager.getPromotionCommon(productDetailInfoRsp.getSkuid());
        List<TemplateMessageNoticeData.Keyword> keywords = new ArrayList<>();
        TemplateMessageNoticeData.Keyword keyword1 = new TemplateMessageNoticeData.Keyword();
        keyword1.setName("keyword1");
        keyword1.setValue(name);
        keywords.add(keyword1);
        TemplateMessageNoticeData.Keyword keyword2 = new TemplateMessageNoticeData.Keyword();
        keyword2.setName("keyword2");
        keyword2.setValue(
            "买" + productDetailInfoRsp.getFinalPlusPriceCount() + "件预估单价" + productDetailInfoRsp.getFinalPlusPrice() +
                "(plus)");
        keywords.add(keyword2);
        TemplateMessageNoticeData.Keyword keyword3 = new TemplateMessageNoticeData.Keyword();
        keyword3.setName("keyword3");
        keyword3.setValue(productDetailInfoRsp.getPromotionDes() == null ? "" : productDetailInfoRsp.getPromotionDes());
        keywords.add(keyword3);
        TemplateMessageNoticeData.Keyword keyword4 = new TemplateMessageNoticeData.Keyword();
        keyword4.setName("keyword4");
        keyword4.setValue(productDetailInfoRsp.getCouponDes() == null ? "" : productDetailInfoRsp.getCouponDes());
        keywords.add(keyword4);
        TemplateMessageNoticeData.Keyword keyword5 = new TemplateMessageNoticeData.Keyword();
        keyword5.setName("keyword5");
        keyword5.setValue(productDetailInfoRsp.getPlusDes() == null ? "" : productDetailInfoRsp.getPlusDes());
        keywords.add(keyword5);
        TemplateMessageNoticeData.Keyword keyword6 = new TemplateMessageNoticeData.Keyword();
        keyword6.setName("keyword6");
        keyword6.setValue(DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss").format(LocalDateTime.now()));
        keywords.add(keyword6);

        wechatCoreUtil.sendTemplateMessage(RedisValueHelper.getAccessToken(), openid,
            "notice", promotionLink, keywords);
    }
}
